<template>
  <div>
    <div class="address-content">
      <div class="address-header">
        <h3>{{ localEditingAddress.id ? '编辑地址' : '添加地址' }}</h3>
      </div>
      <div class="address-body">
        <form @submit.prevent="saveAddress">
          <div class="form-group">
            <label>收货人</label>
            <input type="text" v-model="localEditingAddress.recvName" placeholder="请输入收货人姓名" required>
          </div>
          <div class="form-group">
            <label>手机号码</label>
            <input type="tel" v-model="localEditingAddress.recvMobile" placeholder="请输入手机号码" required>
          </div>
          <div class="form-group">
            <label>省/自治区/直辖市/特别行政区</label>
            <select v-model="pIndex" required>
              <option value="9999">请选择</option>
              <option v-for="(item,index) in provinces" :value="index" :key="index">{{ item.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>地级市/地区/自治州/盟</label>
            <select v-model="cIndex" required>
              <option value="9999">请选择</option>
              <option v-for="(item,index) in cities" :value="index" :key="index">{{ item.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>区/县/自治县/县级市</label>
            <select v-model="countyIndex" required>
              <option value="9999">请选择</option>
              <option v-for="(item,index) in counties" :value="index" :key="index">{{ item.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>街道/镇/乡</label>
            <select v-model="sIndex" required>
              <option value="9999">请选择</option>
              <option v-for="(item,index) in streets" :value="index" :key="index">{{ item.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>详细地址</label>
            <textarea v-model="localEditingAddress.detail" placeholder="请输入详细地址，如街道、楼牌号等"
                      required></textarea>
          </div>
          <div class="form-group">
            <label style="display: inline-block!important;width: inherit">
              <input type="checkbox" v-model="localEditingAddress.isDefault">设为默认地址
            </label>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="$emit('close-modal')">取消</button>
            <button type="button" class="btn btn-primary" @click="saveAddress()">保存地址</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, toRefs, watch} from 'vue';
import {ElMessage} from "element-plus";
import districts from '@/config/district.js';
import apis from '@/config/api-config.js'
import getResponse from "@assets/js/http-client.js";
import {validateMobile} from "@assets/js/form-data-validate.js";

const district = reactive({
  provinces: districts,
  pIndex: 9999,
  cities: [],
  cIndex: 9999,
  counties: [],
  countyIndex: 9999,
  streets: [],
  sIndex: 9999
})
const {provinces, pIndex, cities, cIndex, counties, countyIndex, streets, sIndex} = toRefs(district);

onMounted(() => {
  watch(pIndex, (newVal) => {
    setLowerLevelSelect(1);
    if (9999 === newVal) {
      return;
    }
    cities.value = provinces.value[newVal].districts;
    localEditingAddress.value.province = provinces.value[newVal].name;
  });
  watch(cIndex, (newVal) => {
    setLowerLevelSelect(2);
    if (9999 === newVal) {
      return;
    }
    counties.value = cities.value[newVal].districts;
    localEditingAddress.value.city = cities.value[newVal].name;
  });
  watch(countyIndex, (newVal) => {
    setLowerLevelSelect(3);
    if (9999 === newVal) {
      return;
    }
    streets.value = counties.value[newVal].districts;
    localEditingAddress.value.district = counties.value[newVal].name;
  });
  watch(sIndex, (newVal) => {
    if (9999 != newVal) {
      localEditingAddress.value.street = streets.value[newVal].name;
    }
  });
})
/**
 * 设置下一级行政地区选中项
 */
const setLowerLevelSelect = (currentLevel) => {
  if (currentLevel < 1 || currentLevel > 3) {
    return;
  }
  sIndex.value = 9999;
  if (currentLevel < 3) {
    countyIndex.value = 9999;
    streets.value = [];
  }
  if (1 === currentLevel) {
    cIndex.value = 9999;
    counties.value = [];
  }


}
// 添加props定义
const props = defineProps({
  editingAddress: {
    type: Object,
    default: null
  }
});
//编辑的地址
const localEditingAddress = ref(null);
// 监听props变化，更新本地数据
watch(() => props.editingAddress, (newVal) => {
  if (newVal) {
    localEditingAddress.value = {...newVal};
    if (1 === localEditingAddress.value.isDefault) {
      localEditingAddress.value.isDefault = true;
    } else {
      localEditingAddress.value.isDefault = false;
    }
    // 初始化选择器
    let $pIndex = provinces.value.findIndex(item => item.name === newVal.province);
    if (-1 === $pIndex) {
      //警告
      return;
    }
    pIndex.value = $pIndex;
    cities.value = provinces.value[$pIndex].districts;
    let $cIndex = cities.value.findIndex(item => item.name === newVal.city);
    if (-1 === $cIndex) {
      return;
    }
    cIndex.value = $cIndex;
    counties.value = cities.value[$cIndex].districts;
    let $countyIndex = counties.value.findIndex(item => item.name === newVal.district);
    if (-1 === $countyIndex) {
      return;
    }
    countyIndex.value = $countyIndex;
    streets.value = counties.value[$countyIndex].districts;
    let $sIndex = streets.value.findIndex(item => item.name === newVal.street);
    if (-1 === $sIndex) {
      return;
    }
    sIndex.value = $sIndex;
  } else {
    // 重置为初始状态
    localEditingAddress.value = {
      id: null,
      recvName: '',
      recvMobile: '',
      province: '',
      city: '',
      district: '',
      street: '',
      detail: '',
      isDefault: false
    }
  }
}, {immediate: true});

const emit = defineEmits(['save-address'])

// 保存地址
const saveAddress = async () => {
  let address = {...localEditingAddress.value};
  //验证数据
  if (!address.recvName) {
    ElMessage.warning('请输入姓名');
    return;
  }
  if (!address.recvMobile) {
    ElMessage.warning('请输入手机号');
    return;
  }
  if (!validateMobile(address.recvMobile)) {
    ElMessage.warning('输入的手机号有误');
    return;
  }
  if (!address.province) {
    ElMessage.warning('请选择省份');
    return;
  }
  if (!address.city) {
    ElMessage.warning('请选择地级市');
    return;
  }
  if (!address.district) {
    ElMessage.warning('请选择区/县级市');
    return;
  }
  if (!address.street) {
    ElMessage.warning('请选择乡镇/街道');
    return;
  }
  if (!address.detail) {
    ElMessage.warning('请填写详细地址');
    return;
  }
  if (address.isDefault) {
    address.isDefault = 1;
  } else {
    address.isDefault = 2;
  }
  let success;
  if (address.id === null) {
    //新增加地址
    success = await createAddress(address);
  } else {
    //修改地址
    success = await modifyAddress(address);
  }
  if (success) {
    emit('save-address', address);
  }
}
/**
 * 新增地址
 */
const createAddress = async (address) => {
  //删除id,否则后端返回400错误状态码
  delete address.id;
  let url = apis.address.create.url;
  let type = apis.address.create.type;
  let result = await getResponse(url, type, address);
  if (200 != result.code) {
    ElMessage.warning(result.message);
    return false;
  }
  return true;
}

//修改地址
const modifyAddress = async (address) => {
  let url = apis.address.modify.url;
  let type = apis.address.modify.type;
  let result = await getResponse(url, type, address);
  if (200 != result.code) {
    ElMessage.warning(result.message);
    return false;
  }
  return true;
}


</script>

<style scoped>
.address-content {
  background: #fff;
  width: 100%;
  min-width: 480px !important;
  border-radius: 12px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 16px;
  border-bottom: 1px solid #eee;
}

.address-header h3 {
  margin: 0;
  color: #333;
  font-weight: 600;
}

.address-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #444;
  font-size: 14px;
}

.form-group input:not([type="checkbox"]),
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.form-group textarea {
  min-height: 100px;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

.btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #666;
}

.btn-secondary:hover {
  background-color: #e0e0e0;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #337ecc;
}
</style>